<template>
  <div class="investmentd">
    <vheader :pageTitle="goodDetail.subjectName"></vheader>
    <div class="main">
      <div class="main-container">
        <spliter></spliter>
        <div class="investmentd-caninveste">
          <p>可投金额：</p>
          <span>{{ goodDetail.canCastAmt }}元</span>
        </div>
        <spliter></spliter>

        <div class="investmentd-content">
          <p>借款利率：<span>{{ goodDetail.borrowRate + goodDetail.borrowAwardRate }}%</span></p>
          <p>投资期限：<span>{{ goodDetail.borrowDay }}天</span></p>
          <div class="investmentd-content-line"></div>
          <p>投资金额<strong> 100元起投</strong></p>
          <div class="investmentd-content-input">
            <input type="number" v-model="investMoney">
            <span>元</span>
          </div>
          <p>预计收益：<span>{{ inteset.toFixed(2) }}元</span></p>
          <div class="investmentd-content-line"></div>
          <div class="investmentd-caninveste">
            <p>账户余额：</p>
            <span>{{ balance.toFixed(2) }}元</span>
          </div>
        </div>
        <spliter></spliter>
        
        <div class="investmentd-redcard">
          <div class="investmentd-redcard-top">
            <p>可用优惠 <strong>{{ canUseRedCard.length }}</strong> 个</p>
            <span class="icon-top" @click="toggleRed" :style="{transform: redCardContentShow ? 'rotate(0)' : 'rotate(180deg)'}"></span>
          </div>
          <div class="investmentd-redcard-cont">
            <p>已为您匹配最佳方案 (<span v-show="best.couponType === 1">+{{ best.couponMoney }}元</span> <span v-show="best.couponType === 2">+{{ best.couponMoney }}%</span>)</p>
          </div>
          <div class="investmentd-redcard-content">
            <ul v-show="redCardContentShow">
              <li v-for="(item, index) in canUseRedCard" @click="selectRedCard(item)">
                <img :src="item.couponType === 1 ? dikou_img : jiaxi_img">
                <span v-if="item.couponType === 1" :style="{color: '#ff4133'}">￥{{item.couponMoney}}元</span>
                <span v-else :style="{color: '#3fadf9'}">{{item.couponMoney.toFixed(2)}}%</span>
              </li>
              <p>*只能选取一种类型的优惠</p>
            </ul>
          </div>
        </div>
        <div class="investmentd-agreement">
          <p>
            <label :class="isread ? 'icon-Selected' : 'icon-Unchecked'" for="isread"></label>
            <strong>我已阅读并同意分秒金融</strong>
            <span @click="toServiceAgreement">《借贷及服务协议》</span>
            <span @click="toWarn">《风险提示书》</span>
            <strong>市场有风险，投资需谨慎。</strong>
          </p>
          <input type="checkbox" id="isread" v-model="isread" :style="{display: 'none'}">
        </div>
      </div>

    </div>

    <div class="footer">
      <div class="investmentd-footer" v-show="!isFocus">
        <div class="combtn-wrapper">
          <combtn v-if="isEnough" @click="invest" :disabled="btnDisabled"></combtn>
          <combtn v-else text="立即充值" @click="recharge" :disabled="btnDisabled"></combtn>        
        </div>
        <p v-if="isEnough">市场有风险 投资需谨慎</p>
        <p v-else>账户余额不足</p>
      </div>
    </div>
    <vmask v-show="maskShow"></vmask>
  </div>
</template>

<script>
  import vheader from 'components/common/comHead'
  import spliter from 'components/common/spliter'
  import combtn from 'components/common/comBtn'
  import { Toast, Indicator } from 'mint-ui'
  import mask from 'components/common/mask'
  import popUp from 'components/common/popup/popup.js'

  export default {
    data () {
      return {
        acctKey: null,
        goodDetail: {},
        redCrads: [],
        canUseRedCard: [],
        investMoney: 2000,
        redCardContentShow: false,
        inteset: 0,
        best: {
          couponType: 0,
          couponMoney: 0,
          couponCode: ''
        },
        isread: false,
        isFocus: false,
        btnDisabled: false,
        dikou_img: require('assets/tzqr_dikou@3x.png'),
        jiaxi_img: require('assets/tzqr_jiaxi@3x.png'),
        maskShow: false
      }
    },
    watch: {
      investMoney (newValue) {
        this.inteset = (newValue / 100) * (this.goodDetail.borrowRate + this.goodDetail.borrowAwardRate) * (this.goodDetail.borrowDay / 360) // 计算收益

        this.canUseRedCard = []
        this.redCrads.forEach((item) => {
          // 没有金额限制的红包
          if (item.minInvestMoney === 0) {
            if (item.cycleValue === 0) {
              this.canUseRedCard.push(item) // 无条件红包
              return
            }
            if (item.cycleValue >= this.goodDetail.borrowDay) {
              this.canUseRedCard.push(item) // 红包的天数要大于投资天数
              return
            }
          }
          // 投资金额必须大于红包的最小投资金额
          if (newValue >= item.minInvestMoney) {
            if (item.cycleValue === 0) {
              this.canUseRedCard.push(item) // 无条件红包
              return
            }
            if (item.cycleValue >= this.goodDetail.borrowDay) {
              this.canUseRedCard.push(item) // 红包的天数要大于投资天数
              return
            }
          }
        }) // 红包使用规则
      },
      canUseRedCard (newValue) {
        // 没有可以使用的红包
        if (newValue.length === 0) {
          this.best = {
            couponType: 0,
            couponMoney: 0,
            couponCode: ''
          }
          return
        }
        const reds = []
        const cards = []
        newValue.forEach((item) => {
          if (item.couponType === 1) {
            reds.push(item)
          } else {
            cards.push(item)
          }
        })

        this.best = reds[0] || cards[0]
      }
    },
    computed: {
      balance () {
        return this.$store.state.user.balance
      },
      isEnough () { // 钱是否足够
        if (this.balance === 0) {
          return false
        }
        return (this.investMoney - this.best.couponMoney) <= this.balance
      }
    },
    methods: {
      toggleRed () {
        this.redCardContentShow = !this.redCardContentShow
      },
      selectRedCard (item) {
        console.log(item)
        if (this.best.couponCode === item.couponCode) {
          this.best = {
            couponType: 0,
            couponMoney: 0,
            couponCode: ''
          }
          return
        }
        if (item.couponType === 1) {
          this.best = item
        } else {
          this.best = item
        }
      },
      invest () { // 投资
        const that = this
        if (!this.isread) {
          Toast('请阅读服务协议')
          return
        }
        if (this.investMoney < 100) {
          Toast('投资额度不能少于100')
        }
        this.btnDisabled = true // 点击后禁用按钮
        Indicator.open()
        this.$http.post('/api/borrow/borrowInfo/buyer', 'acctKey=' + this.acctKey + '&borrowOrder=' + this.$route.params.borrowOrder + '&buyCount=' + this.investMoney + '&channelCode=2&couponCode=' + this.best.couponCode)
        .then((res) => {
          if (res.data.success) {
            this.btnDisabled = false
            console.log('投标成功')
            Indicator.close()

            // 投资成功后的弹窗
            this.maskShow = true
            const popup = popUp({
              container: '.investmentd',
              innerHtml: '<p style="text-align: center">恭喜您，投资成功！</p><p style="text-align: center">去查看投资详情？</p>',
              type: 'confirm',
              negtiveText: '取消',
              positiveText: '确定'
            })
            popup.positive = () => {
              that.$router.push('/assetsManagement')
              popup.close()
              that.maskShow = false
            }
            popup.negtive = () => {
              that.$router.go(-1)
              popup.close()
              that.maskShow = false
              console.log(that.$route.path)
            }
          } else {
            Indicator.close()
            Toast(res.data.msg)
            this.btnDisabled = false
          }
        })
        .catch((err) => {
          this.btnDisabled = false
          console.log(err)
          Indicator.close()
        })
      },
      recharge () {
        this.btnDisabled = true
        this.$router.push('/rechargeMoney') // 充值页面
      },
      toServiceAgreement () {
        this.$router.push('/serviceAgreement')
      },
      toWarn () {
        this.$router.push('/warn')
      }
    },
    created () {
      this.acctKey = this.getUserCookie('acctKey')
      // 获取标的详情
      const getSubject = () => {
        return this.$http.get(`/api/borrow/borrowInfo/view?borrowOrder=${this.$route.params.borrowOrder}`)
      }
      // 获取红包
      const getRedCard = () => {
        return this.$http.get(`/api/member/memberCouponList?acctKey=${this.acctKey}&currentPage=1&numPerPage=999&couponType=-1`)
      }
      // 同时发起请求
      this.$http.all([getSubject(), getRedCard()])
        .then(this.$http.spread((res1, res2) => {
          if (res1.data.success) {
            this.goodDetail = res1.data.data
            console.log(this.goodDetail)
            this.inteset = 20 * (this.goodDetail.borrowRate + this.goodDetail.borrowAwardRate) * (this.goodDetail.borrowDay / 360) // 计算收益
          } else {
            console.log(res1.data.msg)
          }
          if (res2.data.success) {
            this.redCrads = res2.data.data.list
          } else {
            console.log(res2.data.msg)
          }
        }))
        .catch((err) => {
          console.log(err)
        })
    },
    components: {
      vheader,
      spliter,
      combtn,
      vmask: mask
    }
  }
</script>

<style lang='scss'>
  @import '../../common/scss/_variable.scss';

  .investmentd {
    display: flex;
    flex-direction: column;
    height: 100%;
    font-size: 32px;
    color: $base-666;
    background: $base-fff;
    .main {
      -webkit-overflow-scrolling : touch;
      overflow: auto;
      height: 9999px;
      min-height: 700px;
      &-container {
        overflow: auto;
      }
    }
    .footer {
      flex: none;
    }
    &-caninveste {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 110px;
      padding: 0 30px;
      span {
        color: $base-ff6c00;
        font-size: 40px;
      }
    }
    &-content {
      padding: 0 30px;
      p {
        margin: 40px 0;
        span {
          color: $base-ff6c00;
        }
        strong {
          font-size: 28px;
          color: $base-999;
        }
      }
      &-line {
        height: 2px;
        background: $base-e5e5e5;
      }
      & .investmentd-caninveste {
        padding: 0;
      }
      &-input {
        position: relative;
        input {
          box-sizing: border-box;
          outline: none;
          width: 100%;
          height: 96px;
          text-align: right;
          border: 1px solid #ff4133;
          font-size: 50px;
          color: $base-ff6c00;
          padding-right: 60px;
        }
        span {
          position: absolute;
          right: 0;
          top: 0;
          display: inline-block;
          width: 60px;
          text-align: center;
          line-height: 100px;
          color: #999;
        }
      }
    }
    &-redcard {
      &-top {
        padding: 30px 30px 30px 30px;
        display: flex;
        justify-content: space-between;
        span {
          display: inline-block;
          color: $base-ff6c00;
          transition: all .5s ease;
        }
        &>p {
          strong {
            color: $base-ff6c00;
          }
        }
      }
      &-cont {
        p {
          font-size: 28px;
          text-indent: 30px;
          color: $base-999;
          margin-bottom: 30px;
          span {
            font-size: 30px;
          }
          span:nth-child(1) {
            color: $base-ff6c00;
          }
          span:nth-child(2) {
            color: $base-3fadf9;
          }
        }
      }

      &-content {
        ul {
          position: relative;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          padding: 0 70px 20px 70px;
          li {
            position: relative;
            margin-bottom: 30px;
            font-size: 38px;
            img {
              width: 268px;
            }
            span {
              top: 0;
              left: 0;
              position: absolute;
              display: inline-block;
              width: 100%;
              line-height: 136px;
              text-align: center;
              text-indent: -30px;
            }
          }
          p {
            position: absolute;
            bottom: 10px;
            left: 70px;
            font-size: 28px;
            color: #999;
          }
        }
      }
    }
    &-agreement {
      height: 126px;
      background: $base-f8f8f8;
      text-align: center;
      p {
        font-size: 28px;
        color: $base-3fadf9;
        line-height: 46px;
        padding: 20px 0;
        label {
          display: inline-block;
          width: 30px;
          height: 30px;
          color: $base-3fadf9;
        }
        span {
          line-height: 30px;
          display: inline;
          text-decoration: underline;
        }
      }
    }
    &-footer {
      width: 100%;
      padding: 30px 0 0 0;
      border-top: 1px solid $base-f8f8f8;
      background: $base-fff;
      text-align: center;
      .combtn-wrapper {
        margin: 0 auto;
      }
      & > p {
        font-size: 28px;
        color: $base-999;
        line-height: 60px;
      }
    }
  }
</style>
